<!-- 
返回顶部功能的组件
 * @Author: zuobufan
 * @Location: 中杰科技研发中心
 * @LastEditors: zuobufan
 * @LastEditTime: 2021-09-27 16:37:00
 -->
<template>
  <div
    class="back_top"
    @mouseover="enterBackTop"
    @mouseout="outBackTop"
    ref="backTop"
    :style="{ opacity: opacity }"
    v-show="gotop"
    @click="handleScrollTop"
  >
    <van-icon name="back-top" size="40px" /> <!-- 返回图标 -->
  </div>
</template>
<script>
export default {
  data() {
    return {
      opacity: ".3",
      gotop: false,
      scrollHeight: 300,
      scrollTop: 0
    };
  },
  methods: {
    enterBackTop() {
      this.opacity = ".5";
    },
    outBackTop() {
      this.opacity = ".3";
    },
    handleScroll(e) {
      const that = this;
      const scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      that.scrollTop = scrollTop;
      that.scrollTop > this.scrollHeight
        ? (this.gotop = true)
        : (this.gotop = false);
    },
    handleScrollTop() {
      // this.$nextTick(() => {
      //   this.ele.scrollIntoView({ behavior: 'smooth' });
      // });
      const that = this;
      const timer = setInterval(() => {
        const ispeed = Math.floor(-that.scrollTop / 5);
        document.documentElement.scrollTop = document.body.scrollTop =
          that.scrollTop + ispeed;
        if (that.scrollTop === 0) {
          clearInterval(timer);
        }
      }, 16);
    }
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll, true); // 注册滚动事件
  }
};
</script>
<style lang="less" scoped>
.van-icon{
    position: fixed;
    bottom: 120px;
    right: 30px;
}
.van-icon:hover{
    opacity: 1;
}
</style>

